//package wmmd.ask;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import db.DatabaseConnector;

public class PostQuestion extends HttpServlet {
    
    // doPost method included for POST requests
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        doGet(request, response);
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        // The JSP document passes in which db table to use
        String tName = "questions";
        String webroot = request.getParameter("webroot");
        
        //Variables for the database connection
        DatabaseConnector con1 = new DatabaseConnector(DatabaseConnector.getDatabaseType());;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
            con1 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
            
            // Variables for all of the values we need to mail & add the question to the db.
            // Note: the db automatically assigns an ID to a new record.
            String askedBy = request.getRemoteUser();
            String lPrivacy = request.getParameter("Privacy");
            String lMethod = request.getParameter("Method");
            String lQuestion = request.getParameter("Quest");
            int display = 0;
            
            // If REMOTEUSER is null (i.e. testing), assign the name 'Guest'
            if(askedBy==null) {
                askedBy = "Guest  ";
            }
            
            // Remove characters from the user's question which may screw up the SQL query.
            lQuestion= lQuestion.replace('\'', '`');
            lQuestion= lQuestion.replace('\"', '|');
            
            // If the user is willing to have the question made public,
            // insert the question into the db.
            if(lPrivacy.equals("Public")) {
                // Set the response method to "Post to Library"
                lMethod = "Post to Library";
                display = 1;
                
                String SQL = "INSERT INTO " + tName + "(Display, FAQ, CategoryID, AskedBy, Question) VALUES (?,?,?,?,?)";
                con1.freeformSQL(SQL,new Object[]{display, 0, 1, askedBy, lQuestion});
            }
            
            // Create the header for the resource info
            out.println("<table border=\"0\" cellpadding=\"3\" width=\"615\">");
            out.print("<tr><td colspan=\"2\" bgcolor=\"cccccc\">");
            out.println("<b>Here is what was sent:</b></td></tr>");
            
            out.print("<tr><td width=\"150\" bgcolor=\"eeeeee\"><b>Posted by:</b></td><td width=\"425\">");
            out.println(askedBy + "</td></tr>");
            out.print("<tr><td bgcolor=\"eeeeee\"><b>Response method:</b></td><td>");
            out.println(lPrivacy + " (" + lMethod + ")</td></tr>");
            out.println("<tr><td valign=\"top\" bgcolor=\"eeeeee\"><b>Question:</b></td>");
            out.println("<td>" + lQuestion);
            out.println("</td></tr></table>");
            
            // Send mail to the administrators
            this.sendMail(request, askedBy);
            //sendMail(request, response, askedBy, mailroot);
        } finally {
            con1.CleanUp();
        }
    }
        
    public void sendMail(HttpServletRequest request, String author) {
        StringBuffer buff = new StringBuffer();
        
        String lemailTo = request.getParameter("emailTo");
        String lemailFrom = request.getParameter("emailFrom");
        String lemailSubject = request.getParameter("emailSubject");
        String lPrivacy = request.getParameter("Privacy");
        String lMethod = request.getParameter("Method");
        String lQuestion = request.getParameter("Quest");
        
        // If the Method parameter is null, set the string to "Post to Library"
        // just for aesthetic reasons.
        if(lMethod==null) {
            lMethod = "Post to Library";
        }
        
        try {
            Mailer m = new Mailer("smtp.pitt.edu");
            //m.setRecipients(lemailTo);
            m.setRecipients("jpg14@pitt.edu");
            m.setSender(lemailFrom);
            m.setSubject(lemailSubject);
            
            // Write the actual contents of the email;           
            buff.append("You are receiving this message because a new question has been ");
            buff.append("submitted from the website.  Details are listed below.");
            if(lPrivacy.equals("Public")) {
                buff.append(writeQuestionURL());
            }
            buff.append("\r\n\r\nPOSTED BY: " + author + "\r\n");
            buff.append("RESPONSE METHOD: " + lPrivacy + " (" + lMethod + ")\r\n\r\n");
            buff.append("QUESTION:\r\n");
            buff.append(lQuestion + "\r\n");
            
            m.setMessage(buff.toString());
            m.send();
         } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // Gets the ID of the new record, and returns a string containing the URL
    // of the admin page where the administrator can post his/her response.
    public String writeQuestionURL() throws IOException {
        
        // The ID string we will be returning
        String id = "";
        StringBuffer buff = new StringBuffer();
        
        //Variables for the database connection
        DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
                
        try {
            String SQL = "SELECT MAX(ID) FROM questions";
            String[][] rs = con.selectSQL(SQL, 1);
            try {
                id = rs[0][0];
            } catch (Exception e){
                System.out.println("Error with the SQL... "+e.getMessage());
            }
            
            buff.append(" Because the sender is allowing you to make the question public, ");
            buff.append("you can post your response to the question on the website by following this link:\r\n\r\n");
            buff.append("http://talad.sis.pitt.edu/VAW/adminapps/");
            buff.append("EditQuestion.jsp?ID=" + id + "\r\n\r\n");
            buff.append("The question will not become public in the Questions Library until you have posted your response. ");
            buff.append("Please note that you will be prompted for your username and password to access the website. ");
        } finally {
            con.CleanUp();
        }
        return buff.toString();
    }
}